package com.fh.rabbit;



import cn.hutool.json.JSONUtil;
import com.fh.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MyAckReceiver implements ChannelAwareMessageListener {
    @Autowired
    private OrderService orderService;
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理
            // ObjectMapper mapper=new ObjectMapper();
            // JavaType javaType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
            // Map<String, Object> resultMap = mapper.readValue(message.getBody(),javaType);

            Map<String, Object> resultMap = (Map<String, Object>) SerializationUtils.deserialize(message.getBody());
            if ("orderQueue".equals(message.getMessageProperties().getConsumerQueue())){
                System.out.println("消费的消息来自的队列名为："+message.getMessageProperties().getConsumerQueue());
                // System.out.println("消息成功消费到  messageId:"+resultMap.get("content"));
                System.out.println("消息成功消费到  messageId:"+ JSONUtil.toJsonStr(resultMap));
                System.out.println("执行TestDirectQueue中的消息的业务处理流程......");

            }
            String orderSn = (String) resultMap.get("content");
            //走自己的业务逻辑
            orderService.rollBackStock(orderSn);

            // 正常的确认消息
            channel.basicAck(deliveryTag, true);
//       channel.basicReject(deliveryTag, true);//为true会重新放回队列
        } catch (Exception e) {
            //确认反馈 两种方式一种是 nack 不需要重新进入队列 reject :需要重新进入队列
            channel.basicReject(deliveryTag, false);
            e.printStackTrace();
        }

    }
}